package com.qiche.util;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.qiche.redis.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * Ticket : 获取微信授权
 *
 * @author zhangds
 * @since 2017-04-19 12:55
 */
@Component
public class Ticket {

	/*
	 * @Resource private RedisCache redisCache;
	 */
	@Resource
	private Token token;

	@Autowired
	private RedisService redisService;


	private Gson gson = new Gson();

	/**
	 * 读取ticket首先读取本地的缓存如果不存在这从新从微信读取
	 * 
	 * @return
	 */
	public String get_ticket() {
		String ticket = redisService.get("ticket").toString();
		if (null == ticket || "".equals(ticket)) {
			JsonObject jsonObj = this.getTocketFromWx();
			ticket = jsonObj.get("ticket").getAsString();
			redisService.set("ticket",ticket,7200L);
			//redis.setString("ticket", ticket);
			//redis.setExpireTime("ticket", 7200);
		}
		return ticket;
	}

	/**
	 * 从微信获取ticket
	 * 
	 * @return
	 */
	private JsonObject getTocketFromWx() {
		String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + token.get_access_token()
				+ "&type=jsapi";
		JsonObject jsonObject = gson.fromJson(HttpUtils.sendGet(url), JsonObject.class);
		return jsonObject;
	}

}
